package com.videoplatform.controller;

import com.videoplatform.entity.Video;
import com.videoplatform.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Controller
@RequestMapping("/api/video")
public class VideoController {
    
    @Autowired
    private VideoService videoService;
    
    /**
     * 获取所有视频列表
     */
    @GetMapping("/list")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getVideoList() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Video> videos = videoService.getAllActiveVideos();
            response.put("success", true);
            response.put("videos", videos);
            response.put("count", videos.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取视频列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 根据ID获取视频信息
     */
    @GetMapping("/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getVideoInfo(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<Video> videoOpt = videoService.getVideoById(id);
            
            if (videoOpt.isPresent()) {
                Video video = videoOpt.get();
                response.put("success", true);
                response.put("video", video);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "视频不存在");
                return ResponseEntity.notFound().build();
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取视频信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 流式播放视频文件
     */
    @GetMapping("/stream/{id}")
    public ResponseEntity<Resource> streamVideo(@PathVariable Long id,
                                              @RequestHeader(value = "Range", required = false) String rangeHeader) {
        
        try {
            Optional<Video> videoOpt = videoService.getVideoById(id);
            
            if (!videoOpt.isPresent()) {
                return ResponseEntity.notFound().build();
            }
            
            Video video = videoOpt.get();
            Path filePath = Paths.get(video.getFilePath());
            
            if (!Files.exists(filePath)) {
                return ResponseEntity.notFound().build();
            }
            
            // 增加观看次数
            videoService.incrementViewCount(id);
            
            File file = filePath.toFile();
            long fileLength = file.length();
            
            // 处理Range请求（支持视频拖拽）
            if (rangeHeader != null && rangeHeader.startsWith("bytes=")) {
                String[] ranges = rangeHeader.substring(6).split("-");
                long start = Long.parseLong(ranges[0]);
                long end = ranges.length > 1 && !ranges[1].isEmpty() ? 
                          Long.parseLong(ranges[1]) : fileLength - 1;
                
                if (start >= fileLength || end >= fileLength || start > end) {
                    return ResponseEntity.status(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
                            .header(HttpHeaders.CONTENT_RANGE, "bytes */" + fileLength)
                            .build();
                }
                
                long contentLength = end - start + 1;
                
                FileSystemResource resource = new FileSystemResource(file);
                
                return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
                        .header(HttpHeaders.CONTENT_TYPE, getContentType(video.getFileName()))
                        .header(HttpHeaders.ACCEPT_RANGES, "bytes")
                        .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength))
                        .header(HttpHeaders.CONTENT_RANGE, "bytes " + start + "-" + end + "/" + fileLength)
                        .body(resource);
            } else {
                // 完整文件响应
                FileSystemResource resource = new FileSystemResource(file);
                
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_TYPE, getContentType(video.getFileName()))
                        .header(HttpHeaders.ACCEPT_RANGES, "bytes")
                        .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(fileLength))
                        .body(resource);
            }
            
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 搜索视频
     */
    @GetMapping("/search")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> searchVideos(@RequestParam String keyword) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Video> videos = videoService.searchVideos(keyword);
            response.put("success", true);
            response.put("videos", videos);
            response.put("count", videos.size());
            response.put("keyword", keyword);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "搜索失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取热门视频
     */
    @GetMapping("/popular")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getPopularVideos() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Video> videos = videoService.getPopularVideos();
            response.put("success", true);
            response.put("videos", videos);
            response.put("count", videos.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取热门视频失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 删除视频
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteVideo(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean deleted = videoService.deleteVideo(id);
            
            if (deleted) {
                response.put("success", true);
                response.put("message", "视频删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "视频不存在");
                return ResponseEntity.notFound().build();
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取视频统计信息
     */
    @GetMapping("/stats")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getVideoStats() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Map<String, Object> stats = videoService.getPlatformStats(); // Corrected method call and return type
            response.put("success", true);
            response.put("stats", stats);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取统计信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 根据文件名获取Content-Type
     */
    private String getContentType(String fileName) {
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        
        switch (extension) {
            case "mp4":
                return "video/mp4";
            case "avi":
                return "video/x-msvideo";
            case "mov":
                return "video/quicktime";
            case "wmv":
                return "video/x-ms-wmv";
            case "flv":
                return "video/x-flv";
            case "webm":
                return "video/webm";
            case "mkv":
                return "video/x-matroska";
            default:
                return "video/mp4";
        }
    }
}
